package com.unionftech.common.webview.view

import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import android.webkit.WebView
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.webview.WebViewDefaultSetting
import com.unionftech.common.webview.callback.WebViewCallBack

open class BaseWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : WebView(context, attrs, defStyleAttr), BaseWebViewClient.WebViewTouch {
    companion object {
        private const val TAG = "BaseWebView"
    }

    private var webViewCallBack: WebViewCallBack? = null
    private var mHeaders: HashMap<String, String>? = null
    private var isTouchByUser: Boolean = false
    private var redirectIntercept = false
    private var mContext: Context? = null

    init {
        init(context)
    }

    private fun init(context: Context) {
        mContext = context
        //初始化默认设置
        WebViewDefaultSetting.getInstance().toSetting(this)
    }


    fun registerWebViewCallBack(webViewCallBack: WebViewCallBack? = null) {
        this.webViewCallBack = webViewCallBack
        webViewClient = BaseWebViewClient(
            this,
            this.webViewCallBack,
            mHeaders,
            this,
            redirectIntercept
        )
    }

    fun setHeaders(headers: HashMap<String, String>) {
        this.mHeaders = headers
    }

    fun setRedirectIntercept(intercept: Boolean) {
        this.redirectIntercept = intercept
    }

    override fun loadUrl(url: String, additionalHttpHeaders: MutableMap<String, String>) {
        super.loadUrl(url, additionalHttpHeaders)
        LogUtils.d(TAG, "load url: $url")
        resetAllStateInternal(url)
    }

    override fun loadUrl(url: String) {
        if (mHeaders == null) {
            super.loadUrl(url)
        } else {
            super.loadUrl(url, mHeaders!!)
        }
        LogUtils.d(TAG, "load url: $url")
        resetAllStateInternal(url)
    }

    private fun resetAllStateInternal(url: String) {
        if (!TextUtils.isEmpty(url) && url.startsWith("javascript:"))
            return
        resetAllState()
    }

    /**
     * 加载时重置touch状态
     */
    private fun resetAllState() {
        isTouchByUser = false
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> isTouchByUser = true
        }
        return super.onTouchEvent(event)
    }

    override fun isTouchByUser(): Boolean {
        return isTouchByUser
    }

    fun release() {
        stopLoading()
        handler?.removeCallbacksAndMessages(null)
        removeAllViews()
        (parent as? ViewGroup)?.removeView(this)
        webViewCallBack = null
        tag = null
        clearHistory()
        clearCache(true)
    }

}